/*
 * Copyright (c) 2013-2014, starteasy Inc. All Rights Reserved.
 * 
 * Project Name: sample
 * $Id:  2016-11-14 17:11:46 $ 
 */
package cn.starteasy.sample.web.controller.api;

import cn.starteasy.core.common.domain.persistent.SearchEnum;
import cn.starteasy.core.common.domain.persistent.utils.ConditionBuilder;
import cn.starteasy.core.common.domain.wrapper.BooleanWrapper;
import cn.starteasy.sample.service.ITownService;
import cn.starteasy.core.common.domain.view.admin.SearchField;
import cn.starteasy.core.common.domain.wrapper.StringWrapper;
import cn.starteasy.core.common.domain.view.BizData4Page;
import cn.starteasy.core.common.exception.BizException;
import cn.starteasy.core.common.protocol.utils.RtnCodeEnum;

import cn.starteasy.sample.domain.Town;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value="/api")
public class ApiTownController{
    private static final Logger logger = LoggerFactory.getLogger(ApiTownController.class);

    @Autowired
    private ITownService townService;

   /**
     * 新增 区县
     * @param town
     * @return  处理条数
     */
    @ResponseBody
    @RequestMapping(value = "/town", method = RequestMethod.POST)
    public Object addTown(@RequestBody Town town) {
        try {
            String msg = "";

            if(town==null) {
                msg = "添加区县参数不正确";
            }else if(town.getStatus() != null){
                msg = "区县状态不能为空";
            }else if(town.getCreator() != null){
                msg = "区县创建人不能为空";
            }else if(town.getCreateDate() != null){
                msg = "区县创建时间不能为空";
            }else if(town.getLastModifier() != null){
                msg = "区县修改人不能为空";
            }else if(town.getLastModDate() != null){
                msg = "区县修改时间不能为空";
            }

            if(StringUtils.isNotBlank(msg)){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), msg);
            }

            townService.create(town);
            return new BooleanWrapper(true);
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "新增区县异常");
        }
    }


    /**
     * 删除 区县
     *
     * @param {townId} 区县ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/town/{townId}" ,method = RequestMethod.DELETE)
    public Object delTown(@PathVariable String townId) {
        try {
            if(StringUtils.isBlank(townId)){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "删除区县失败，参数不正确");
            }
            townService.deleteByCondition(ConditionBuilder.condition("id", SearchEnum.eq, townId));
            return new BooleanWrapper(true);
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "删除区县异常");
        }
    }


    /**
     * 修改区县数据
     * @param town 提交上来的区县JSON数据
     * @param townId  区县ID
     * @return  修改条数
     */
    @ResponseBody
    @RequestMapping(value = "/town/{townId}", method = RequestMethod.PATCH)
    public StringWrapper editTown(@RequestBody Town town, @PathVariable String townId) {
        try {
            String msg = "";
            if(town==null) {
                msg = "添加区县参数不正确";
            }else if(town.getStatus() != null){
                msg = "区县状态不能为空";
            }else if(town.getCreator() != null){
                msg = "区县创建人不能为空";
            }else if(town.getCreateDate() != null){
                msg = "区县创建时间不能为空";
            }else if(town.getLastModifier() != null){
                msg = "区县修改人不能为空";
            }else if(town.getLastModDate() != null){
                msg = "区县修改时间不能为空";

            }

            if(StringUtils.isNotBlank(msg)){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), msg);
            }

            Town town_old = (Town) townService.view(town.getId());
            if(town==null) {
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "修改失败，系统未找到相关数据");
            }

            if(town.getId() != null){
                town_old.setId(town.getId());
            }
            if(!StringUtils.isBlank(town.getName())){
                town_old.setName(town.getName());
            }
            if(!StringUtils.isBlank(town.getNumber())){
                town_old.setNumber(town.getNumber());
            }
            if(!StringUtils.isBlank(town.getXpoint())){
                town_old.setXpoint(town.getXpoint());
            }
            if(!StringUtils.isBlank(town.getYpoint())){
                town_old.setYpoint(town.getYpoint());
            }
            if(!StringUtils.isBlank(town.getCityId())){
                town_old.setCityId(town.getCityId());
            }
            if(town.getStatus() != null){
                town_old.setStatus(town.getStatus());
            }
            if(town.getCreator() != null){
                town_old.setCreator(town.getCreator());
            }
            if(town.getCreateDate() != null){
                town_old.setCreateDate(town.getCreateDate());
            }
            if(town.getLastModifier() != null){
                town_old.setLastModifier(town.getLastModifier());
            }
            if(town.getLastModDate() != null){
                town_old.setLastModDate(town.getLastModDate());
            }


            int row=townService.edit(town_old);
            if(row > 0) {
                return new StringWrapper("修改区县成功");
            }else{
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "修改区县失败");
            }
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "修改区县数据异常");
        }
    }


    /**
     * 获取单区县实体
     *
     * @param townId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/town/{townId}", method = RequestMethod.GET)
    public Town getTown(@PathVariable String townId) {
        try {
            if(StringUtils.isBlank(townId)){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "参数不正确！");
            }
            Map<String,Object> whereParams = new HashMap<String, Object>();
            whereParams.put("id", townId);
            Town town= (Town) townService.viewOne(null, whereParams, null);
            if(null == town){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "系统未找到区县相关数据！");
            }
            return town;
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "获取单区县实体异常");
        }
    }


    /**
     * 区县数据输出 带分页
     *
     * @param town 过滤条件
     * @param page      第几页
     * @return 业务数据列表实体，最终转换为json数据输出
     * @throws ServletException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/townlist", method = RequestMethod.POST)
    public BizData4Page townlist(Town town, Integer page) {
        try {
            Map<String, Object> whereParams = new HashMap<String, Object>();
            if(town.getId() != null){
                whereParams.put("id", new SearchField("id", "=", town.getId()));
            }
            if(!StringUtils.isBlank(town.getName())){
                whereParams.put("name", new SearchField("name", "like", "%" + town.getName() + "%"));
            }
            if(!StringUtils.isBlank(town.getNumber())){
                whereParams.put("number", new SearchField("number", "like", "%" + town.getNumber() + "%"));
            }
            if(!StringUtils.isBlank(town.getXpoint())){
                whereParams.put("xpoint", new SearchField("xpoint", "like", "%" + town.getXpoint() + "%"));
            }
            if(!StringUtils.isBlank(town.getYpoint())){
                whereParams.put("ypoint", new SearchField("ypoint", "like", "%" + town.getYpoint() + "%"));
            }
            if(!StringUtils.isBlank(town.getCityId())){
                whereParams.put("cityId", new SearchField("cityId", "like", "%" + town.getCityId() + "%"));
            }
            if(town.getStatus() != null){
                whereParams.put("status", new SearchField("status", "=", town.getStatus()));
            }
            if(town.getCreator() != null){
                whereParams.put("creator", new SearchField("creator", "=", town.getCreator()));
            }
            if(town.getCreateDate() != null){
                whereParams.put("createDate", new SearchField("createDate", "=", town.getCreateDate()));
            }
            if(town.getLastModifier() != null){
                whereParams.put("lastModifier", new SearchField("lastModifier", "=", town.getLastModifier()));
            }
            if(town.getLastModDate() != null){
                whereParams.put("lastModDate", new SearchField("lastModDate", "=", town.getLastModDate()));
            }


            //other props filter
            whereParams.put("groupOp", "and");

        return townService.queryPage(null, whereParams, page, 10, 10, null);
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "查询区县数据异常");
        }
    }
}
